package com.cn.demo4.servlet.admin.user;

import com.alibaba.fastjson.JSONObject;
import com.cn.demo4.model.PageModel;
import com.cn.demo4.model.UserModel;
import com.cn.demo4.service.IUserService;
import com.cn.demo4.service.impl.UserServiceImpl;
import com.cn.demo4.util.Tool;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/admin/user/findAll")
public class UserFindAllServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.解决乱码问题
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");

        //得到从前台上传来的值
        String userName = req.getParameter("userName");
        String phone = req.getParameter("phone");
        String email = req.getParameter("email");
        String startBirthday = req.getParameter("startBirthday");
        String endBirthday = req.getParameter("endBirthday");
        String hobby = req.getParameter("hobby");
        String sex = req.getParameter("sex");
        String status = req.getParameter("status");
        status = status == null ? "-1" : status;

        String curPage = req.getParameter("curPage");
        String pageSize = req.getParameter("pageSize");
        //3.封装数据
        UserModel userModel = new UserModel();
        userModel.setUserName(userName);
        userModel.setPhone(phone);
        userModel.setEmail(email);
        userModel.setStartBirthday(startBirthday);
        userModel.setEndBirthday(endBirthday);
        userModel.setHobby(hobby);
        userModel.setSex(sex);
        userModel.setStatus(Tool.stringToInt(status));
        PageModel pageModel = new PageModel();
        pageModel.setPageSize(Tool.toPageSize(pageSize));
        pageModel.setCurPage(Tool.toCurPage(curPage));
        userModel.setPageModel(pageModel);


        //4.调用服务逻辑层
        IUserService iUserService = new UserServiceImpl();
        //5.得到所有数据

        List<UserModel> list = iUserService.findAll(userModel);
        int count = iUserService.getCount(userModel);
        //6.返回结果
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", list);
        jsonObject.put("count",count);
        resp.getWriter().println(jsonObject);
    }
}
